JavaScript - search methods

Revision:


Content

linear vs. binary search document.getElementById(id) querySelectorAll(css-selector) querySelector(css-selector) match(css-selector) - matchAll() closest(css-selector) getElementsByTagName(tag or '*') getElementsByClassName(class) getElementsByName(name) includes()


linear vs. binary search

top

linear search

binary search

code:
            <div class="grid1 spec">
                <div>
                    <p ><b>linear search</b></p>
                    <p id="linear1"></p>
                    <p id="linear2"></p>
                    <p id="linear3"></p>
                    <p id="linear4"></p>
                    <p id="linear5"></p>
                </div>
                <div">
                    <p ><b>binary search</b></p>
                    <p id="binary1"></p>
                    <p id="binary2"></p>
                    <p id="binary3"></p>
                    <p id="binary4"></p>
                    <p id="binary5"></p>
                </div>
            </div>
            <script>
                let linearSearch = (list, value) =>{
                    for(let aa = 0; aa<list.length; aa++){
                        if(list[aa] === value){
                            return aa;
                        }
                    }
                    return -1;
                }
                var list = [12, 45, 48, 5, 451, 2, 34, 43, 54, 66]
                var value = 100;
                var value1 = 45;
                var value2 = 34;
                var value3 = 66;
        
                document.getElementById('linear1').innerHTML = "original list: " + list;
                document.getElementById('linear2').innerHTML = "position: " + linearSearch(list, value);
                document.getElementById('linear3').innerHTML = "position: " + linearSearch(list, value1);
                document.getElementById('linear4').innerHTML = "position: " + linearSearch(list, value2);
                document.getElementById('linear5').innerHTML = "position: " + linearSearch(list, value3);
        
                //sorted array mandatory!!
                let BinarySearch = (list2,val)=>{
                    let left = 0;
                    let right = list2.length - 1;
                    let mid = Math.floor((left + right) / 2);
                    while (list2[mid] !== val && left <= right) {
                        if (val < list2[mid]) {
                            right = mid - 1
                        } else {
                            left = mid + 1
                        }
                        mid = Math.floor((left + right) / 2);
                    }
                    if (list2[mid] === val) {
                        return mid;
                    } else {
                        return -1
                    }
        
                };
                let list2 = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]
                let val1 = 20;
                let val2 = 2;
                let val3 = 26;
                let val4 = 10;
                document.getElementById('binary1').innerHTML = "original list: " + list2;
                document.getElementById('binary2').innerHTML = "position: " + BinarySearch(list2, val1); //should return 9
                document.getElementById('binary3').innerHTML = "position: " + BinarySearch(list2, val2);
                document.getElementById('binary4').innerHTML = "position: " + BinarySearch(list2, val3);
                document.getElementById('binary5').innerHTML = "position: " + BinarySearch(list2, val4);
            </script>
        


document.getElementById(id)

top
Element
code:
                    <div id="element">
                        <div id="element_content">element</div>
                    </div>
                    <script>
                        let element = document.getElementById("element");
                        element.style.background = "lightblue";
                        element.style.marginLeft = "2vw";
                        element.style.fontSize = "1.2vw";
                    </script>
                
Element2
code:
                    <div id="element2">
                        <div id="element-content2">Element2</div>
                    </div>
                    <script>
                        let element2 = document.getElementById("element2")
                        element2.style.background = "orange";
                        element2.style.fontWeight = "bold";
                        element2.style.marginLeft = "5vw";
                        element2.style.fontStyle = "italic";
                    </script> 
                

querySelectorAll(css-selector)

top

a paragraph

second paragraph

third paragraph

fourth paragraph

code:
                <div class="spec">
                    <p class="exam">a paragraph</p>
                    <p class="exam">second paragraph</p>
                    <p class="exam2">third paragraph</p>
                    <p class="exam2">fourth paragraph</p>
                </div>
                <script>
                    let nodeList = document.querySelectorAll('.exam');
                    for (let i = 0; i < nodeList.length; i++){
                        nodeList[i].style.backgroundColor = "red";
                    }
                    for (let i = 0; i < nodeList.length; i++){
                        nodeList[i].style.fontSize = "1.5vw";
                    }
                    let nodeList2 = document.querySelectorAll('.exam2');
                    for (let i = 0; i < nodeList2.length; i++){
                        nodeList2[i].style.backgroundColor = "blue";
                    }
                    for (let i = 0; i < nodeList2.length; i++){
                        nodeList2[i].style.fontSize = ".8vw";
                    }
                </script
            
Box number 1
Box number 2
Box number 3
Box number 4
Box number 5
Box number 6
Box number 7
Box number 8
code:
                <div>
                    <div class="box">Box number 1</div>
                    <div class="box">Box number 2</div>
                    <div data-id="3">Box number 3</div>
                    <div data-id="4">Box number 4</div>
                    <div data-id="5">Box number 5</div>
                    <div class="box2">Box number 6</div>
                    <div class="box2">Box number 7</div>
                    <div class="box2">Box number 8</div>
                </div>
                <script>
                    // select by tag name
                    const group1 = document.querySelectorAll(".box");
                    for (let j = 0; j < group1.length; j++){
                        group1[j].style.backgroundColor = "lightgreen";
                    }
                    // // select by class name
                const group2 = document.querySelectorAll(".box2");
                for (let k = 0; k < group2.length; k++){
                        group2[k].style.backgroundColor = "lightblue";
                    }
                    // // select by attribute
                    const group3 = document.querySelectorAll("[data-id]");
                    for (let l = 0; l < group3.length; l++){
                        group3[l].style.backgroundColor = "yellow";
                    }
                </script>
            


querySelector(css-selector)

top

This is a p element.

This is a p element.

This is a p element.

This is a p element.

code:
                <div class="spec">
                    <p class="q">This is a p element.</p>
                    <p class="q">This is a p element.</p>
        
                    <p class="r">This is a p element.</p>
                    <p class="r">This is a p element.</p>
                    <div class="spec">
                        <a href="https://www.lwitters.com">my website</a><br><br>
                        <a href="http://www.disney.com" target="_blank">disney.com</a><br><br>
                        <a href="http://www.wikipedia.org" target="_top">wikipedia.org</a>
                    </div>
                </div>
                <style>
                    a[target]{background-color: yellow;}
                </style>
                <script>
                    document.querySelector(".q").style.backgroundColor = "red";
                    document.querySelector(".r").style.color = "yellow";
                    document.querySelector("a[target]").style.border = "0.2vw solid red";
                </script>
            

Class 4

Myclass

This is the div p paragraph

div p class

Thist is p id

This is div id
code:
                <div class="spec">
                    <h4 class="myClass">Class 4</h4>  
                    <p class="myClass"> Myclass</p>  
                    <div id="firstid">  
                        <p> This is the div p paragraph</p>  
                        <p class="pclass"> div p class</p>  
                    </div>  
                    <p id="myid"> Thist is p id</p>  
                    <div class="spec" id="divid"> This is div id</div>
        
                </div>  
                <script> 
                    var e=document.querySelector(".myClass");  
                    e.style.color = 'red';
                    e.style.fontSize = "2vw";
                </script>  
            

match(css-selector) - matchAll()

top

code:
                <div>
                    <p id="item1"></p>
                </div>
                <script>
                    function matchString() {
                        var string = "Welcome to this website";
                        var result = string.match(/we/g);
                        document.getElementById("item1").innerHTML = "Output : " + result;
                    } 
                    matchString(); 
                </script>
            

code:
                <div class="spec">
                    <ul id="birds">
                        <li>Orange-winged parrot</li>
                        <li class="endangered">Philippine eagle</li>
                        <li>Great white pelican</li>
                    </ul>
                    <p id="item2"></p>
                </div>
                <script>
                    const birds = document.querySelectorAll('li');
                    for (const bird of birds) {
                        if (bird.matches('.endangered')) {
                            document.getElementById('item2').innerHTML = (`The ${bird.textContent} is endangered!`);
                        }
                    }
                </script>
            

code:
                <div>
                    <p id="item3"></p>
                </div>
                <script>
                    let text = "The rain in SPAIN stays mainly in the plain";
                    let results = text.match(/ain/gi);
                    document.getElementById("item3").innerHTML = results;
                </script>
            

code:
                <div>
                    <p id="item3"></p>
                </div>
                <script>
                    let text = "The rain in SPAIN stays mainly in the plain";
                    let results = text.match(/ain/gi);
                    document.getElementById("item3").innerHTML = results;
                </script>
            

code:
                <div class="spec">
                    <p id="mat1"></p>
                    <p id="mat2"></p>
                </div>
                <script>
                    const strA = "learning to code is learning to create and innovate";
                    // with g flag
                    const regexp1 = /l((earn)ing)/g;
                    const match1 = strA.match(regexp1);
                    console.log(match1); // [ "learning", "learning" ]
                    document.getElementById("mat1").innerHTML = JSON.stringify(match1);
                    // removing g flag
                    const regexp2 = /l((earn)ing)/;
                    const match2 = strA.match(regexp2);
                    console.log(match2, match2.index, match2.input); // [ "learning", "earn" ]
                    document.getElementById("mat2").innerHTML = JSON.stringify(match2);
                </script>
            

code:
                <div class="spec">
                    <p id="mat3"></p>
                    <p id="mat4"></p>
                </div>
                <script>
                    const strB = "learning to code is learning to create and innovate";
                    const regexp3 = "(ea)(t)"; // not a regular expression
                    const matches = strB.matchAll(regexp3);
                    const matches3 = strB.matchAll(); // no regexp passed
                    console.log(Array.from(matches));
                    document.getElementById("mat3").innerHTML = matches;
                    console.log(Array.from(matches3));
                    document.getElementById("mat4").innerHTML = matches3;
                </script>
            

closest(css-selector)

top
Grandparent
Parent
The parent of this div element will be selected.
code:
                <div class="item44"> Grandparent
                    <div class="item44 container">Parent
                    <div id="item44" class="item44">The parent of this div element will be selected.</div>
                    </div>
                </div>
                <style>
                    .container, .item44{background-color: tomato;color: white;padding: 2vw;margin: 1vw;}
                </style>
                <script>
                    const el = document.getElementById("item44");
                    const closest = el.closest(".container");
                    if (closest) {
                        closest.style.border = "4px solid black";
                    }
                </script>
            
code:
                <div>
                    <ul id="one" class="level-1">
                        <li class="top-1">Home</li>
                        <li id="ii" class="top-2">Products
                        <ul class="level-2">
                            <li class="category-1">Clothing</li>
                            <li class="category-2">Electronics
                            <ul class="level-3">
                                <li class="product-1">Camera</li>
                                <li class="product-2">Computer</li>
                                <li class="product-3">Phone</li>
                            </ul>
                            </li>
                            <li class="category-3">Kitchen</li>
                        </ul>
                        </li>
                        <li class="top-3">About</li>
                </ul>
                </div>
                <script>
                    const m = document.querySelector("li.category-1");
                    m.style.color = 'red';
                    const close1 = m.closest("ul");
                    close1.style.background = 'yellow';
                    const close2 = m.closest("li");
                    close2.style.background = 'green';
                </script>
            

getElementsByTagName(tag or '*')

top

Some outer text

Some outer text

Some div1 text

Some div1 text

Some div1 text

Some div2 text

Some div2 text

Some outer text

Some outer text


code:
                <div class="item5 spec" style="width: 35vw; margin: 0 auto;">
                    <p>Some outer text</p>
                    <p>Some outer text</p>
                    <div id="div1" style="border: solid blue 3px">
                        <p>Some div1 text</p>
                        <p>Some div1 text</p>
                        <p>Some div1 text</p>
                        <div id="div2" style="border: solid red 3px">
                            <p>Some div2 text</p>
                            <p>Some div2 text</p>
                        </div>
                    </div>

                    <p>Some outer text</p>
                    <p>Some outer text</p>

                    <button onclick="getAllParaElems();">Show all p elements in document</button>
                    <p id="item6"></p>
                    <button onclick="div1ParaElems();">Show all p elements in div1 element</button><br/>
                    <p id="item7"></p>
                    <button onclick="div2ParaElems();">Show all p elements in div2 element</button>
                    <p id="item8"></p>
                </div>
                <script>
                    function getAllParaElems() {
                            const allParas = document.getElementsByTagName("p");
                            const num = allParas.length;
                            document.getElementById("item6").innerHTML = (`There are ${num} paragraph in this document`);
                        }

                        function div1ParaElems() {
                            const div1 = document.getElementById("div1");
                            const div1Paras = div1.getElementsByTagName("p");
                            const num = div1Paras.length;
                            document.getElementById("item7").innerHTML = (`There are ${num} paragraph in #div1`);
                        }
                        function div2ParaElems() {
                            const div2 = document.getElementById("div2");
                            const div2Paras = div2.getElementsByTagName("p");
                            const num = div2Paras.length;
                            document.getElementById("item8").innerHTML = (`There are ${num} paragraph in #div2`);
                        }
                </script>
            

getElementsByClassName(class)

top
A div with class="example"

A div with class="example"

A p element with class="example".

A span element with class="example".

code:
                <div>            
                    <div class="item10">A div with class="example"</div><br>
                    <div class="item10">A div with class="example"</div>
                    <p class="item10">A p element with class="example".</p>
                    <p>A <span class="item10">span</span> element with class="example".</p>    
                </div>
                <script>
                const collection = document.getElementsByClassName("item10");
                for (let n = 0; n < collection.length; n++) {
                    collection[n].style.backgroundColor = "lightblue";
                    collection[n].style.fontSize = "2vw";
                    collection[n].style.fontStyle = "italic";
                }
                </script>
            

hello world 1

hello world 2

hello world 3

hello world 4

code:
                <div>
                    <div id="parent-id">
                        <p>hello world 1</p>
                        <p class="test">hello world 2</p>
                        <p>hello world 3</p>
                        <p>hello world 4</p>
                    </div>
                    <p id="item11"></p>
                    <p id="item12"></p>
                </div>
                <script>
                    const parentDOM = document.getElementById("parent-id");
                    const test = parentDOM.getElementsByClassName("test"); 
                        // a list of matching elements, *not* the element itself
                    console.log(test); // HTMLCollection[1]
                    item11.innerText = test;
                    const testTarget = parentDOM.getElementsByClassName("test")[0]; 
                        // the first element, as we wanted
                    console.log(testTarget); // <p class="test">hello world 2</p>
                    document.getElementById("item12").innerHTML = testTarget;
                </script>
            


Orange Fruit
Orange Juice
Apple Juice
Something Random
code:
                <div class="spec">
                    <span class="orange fruit">Orange Fruit</span><br>
                    <span class="orange juice">Orange Juice</span><br/>
                    <span class="apple juice">Apple Juice</span><br/>
                    <span class="foo bar">Something Random</span><br/>
                    <textarea id="resultArea" style="width:90%;height:7vw"></textarea>
                </div>
                <script>
                    // getElementsByClassName only selects elements that have both given classes
                    const allOrangeJuiceByClass = document.getElementsByClassName('orange juice');
                    let result = "document.getElementsByClassName('orange juice')";
                    for (let q = 0; q < allOrangeJuiceByClass.length; q++) {
                        result += `\n  ${allOrangeJuiceByClass[q].textContent}`;
                    }
                    // querySelector only selects full complete matches
                    const allOrangeJuiceQuery = document.querySelectorAll('.orange.juice');
                    result += "\n\ndocument.querySelectorAll('.orange.juice')";
                    for (let r = 0; r < allOrangeJuiceQuery.length; r++) {
                        result += `\n  ${allOrangeJuiceQuery[r].textContent}`;
                    }
                    document.getElementById("resultArea").value = result;
                </script>
            
Element1

Element2

This is a paragraph.


This is another paragraph.


This is still another paragraph.

code:
                <div>
                    <div class="example">Element1</div><br>
                    <div class="example">Element2</div><br>
                    <div class="example2"><p>This is a paragraph.</p></div><br>
                    <div class="example2 color"><p>This is another paragraph.</p></div><br>
                    <div class="example2 color"><p>This is still another paragraph.</p></div>
                </div>
                <style>
                    div.example2{border: 0.1vw solid black; padding:0.1vw;}
                </style>
                <script>
                    const collectionA = document.getElementsByClassName("example");
                    collectionA[0].innerHTML = "Hello World!";
        
                    const collectionB = document.getElementsByClassName("example2 color");
                    collectionB[0].style.backgroundColor = "red";
                    collectionB[1].style.backgroundColor = "lightblue";
                </script>
            

getElementsByName(name)

top

Please rate the service:

code:
 
                <div class="spec">
                    <p>Please rate the service:</p>
                        <p>
                            <label for="very-poor">
                                <input type="radio" name="rate" value="Very poor" id="very-poor"> Very poor
                            </label>
                            <label for="poor">
                                <input type="radio" name="rate" value="Poor" id="poor"> Poor
                            </label>
                            <label for="ok">
                                <input type="radio" name="rate" value="OK" id="ok"> OK
                            </label>
                            <label for="good">
                                <input type="radio" name="rate" value="Good"> Good
                            </label>
                            <label for="very-good">
                                <input type="radio" name="rate" value="Very Good" id="very-good"> Very Good
                            </label>
                        </p>
                        <p>
                            <button id="btnRate">Submit</button>
                        </p>
                        <p id="output"></p>
                </div>
                <script>
                    let btn = document.getElementById('btnRate');
                    let output = document.getElementById('output');
                    btn.addEventListener('click', () => {
                        let rates = document.getElementsByName('rate');
                        rates.forEach((rate) => {
                            if (rate.checked) {
                                output.innerText = `You selected: ${rate.value}`;
                            }
                        });

                    });
                </script>
            


includes()

top

code:
                <div>
                    <p id="in1"></p>
                    <p id="in2"></p>
                    <p id="in3"></p>
                    <p id="in4"></p>
                    <p id="in5"></p>
                </div>
                <script>
                    const array1 = [1, 2, 3];
                    document.getElementById("in1").innerHTML = "array : " + array1;
                    document.getElementById("in2").innerHTML = (array1.includes(2));
                    const pets = ['cat', 'dog', 'bat'];    
                    in3.innerText = "pets : " + pets;        
                    document.getElementById("in4").innerHTML = pets.includes("cat");
                    document.getElementById("in5").innerHTML = pets.includes("at");
                </script>
            

code:
                <div class="spec">
                    <p id="in6"></p>
                    <p id="in7"></p>
                </div>
                <script>
                    const array = [10, 11, 3, 20, 5];
                    const includesTwenty = array.includes(20);
                    document.getElementById("in6").innerHTML = "array includes 20: " + includesTwenty;
                    const includesTenTwice = array.includes(10, 1);
                    document.getElementById("in7").innerHTML = "array includes 10 twice: " + includesTenTwice;
                </script>
            

string search()

top

The search() method matches a string against a regular expression. It returns the index (position) of the first match. It returns -1 if no match is found. This method is case sensitive.

code:
                <div class="spec">
                    <p id="search"></p>
                    <p id="search1"></p>
                    <p id="search2"></p>
                    <p id="search3"></p>
                    <p id="search4"></p>
                
                </div>
                <script>
                    let text_a = "Mr. Blue has a blue house"
                    let position = text_a.search("Blue");
                    document.getElementById("search").innerHTML = "position of 'Blue': " + position;
                    let position1 = text_a.search("blue");
                    document.getElementById("search1").innerHTML = "position of 'blue': " + position1;
                    let position2 = text_a.search(/Blue/);
                    document.getElementById("search2").innerHTML = "position of '/Blue/': " + position2;
                    let position3 = text_a.search(/blue/);
                    document.getElementById("search3").innerHTML = "position of '/blue/': " + position3;
                    let position4 = text_a.search(/blue/i);
                    document.getElementById("search4").innerHTML = "position of '/blue/i': " + position4;
                </script>
            

code:
                <div class="spec">
                    <p id="search5"></p>
                    <p id="search6"></p>
                    <p id="search7"></p>
                </div>
                <script>
                    let sentence= "I love JavaScript.";
                    // pattern that searches the first occurence of an uppercase character
                    let regExp = /[A-Z]/;
                    // searching for a match between regExp and given string 
                    let indexReg = sentence.search(regExp);
                    document.getElementById("search5").innerHTML = indexReg; // output: 0
                    let string1 = "JavaScript JavaScript1";
                    // pattern having 'JavaScript' followed by a digit
                    let regExp1 = /(JavaScript)\d/;
                    // searching for a match between regExp and given string
                    let index = string1.search(regExp1);
                    document.getElementById("search6").innerHTML = index; // output: 11
                    let string2 = "I love to code in JavaScript.";
                    // searching word "JavaScript" in the given string
                    let index2 = string2.search("code");
                    document.getElementById("search7").innerHTML = index2; // output: 10
                </script>
            

startsWith()

The startsWith() method checks if a string begins with a specified string


endsWith()

The endsWith() method checks if a string ends with a specified string